package com.zhdl.network.common_client;

import cn.hutool.core.util.HexUtil;
import com.project.command.instruction.strategy.abs.AbsAfterControlCommand;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.project.common.util.ByteHelper;
import com.zhdl.common.ytools.eventbus.center.EventBusCenter;
import com.zhdl.network.common_client.dto.ModbusTcpDto;
import com.zhdl.network.common_client.resp.CommonClientEvent;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service(CommonTcpClientAfter.COMMON_TCP_AFTER_SERVICE)
public class CommonTcpClientAfter extends AbsAfterControlCommand<ModbusTcpDto, ByteBuf> {

    public static final String COMMON_TCP_AFTER_SERVICE = "commonProtocolClientAfter";
    private int printTimes = 0;

    /**
     * 后置处理结果判断
     *
     * @param resp 接受到的回复
     * @return 收到
     */
    @Override
    public boolean afterResultJudge(AfterStrategyParam resp) {
        List<byte[]> receiveDataList = resp.getNewData();
        byte[] receiveData = receiveDataList.get(0);
        //组装分发的数据
        CommonClientEvent protocolEvent = new CommonClientEvent();
        protocolEvent.setPort(resp.getPortKey());
        protocolEvent.setProtocol(resp.getProtocols());
        protocolEvent.setSendCmd(resp.getInstruction());
        protocolEvent.setReceiveData(receiveData);
        EventBusCenter.getEventBus().post(protocolEvent);

        printTimes++;
        if (printTimes == 3000) {
            log.info("COMMON_TCP_AFTER_SERVICE---->{}-发送指令>>>>>>>>{}-收到指令>>>>>>>>{}",
                    resp.getPortKey(), resp.getInstruction(), ByteHelper.byteToString(receiveData));
            printTimes = 0;
        }
        return true;
    }

    /**
     * 判断 读取 3200 状态字数据
     */
    public String getMotorStatus(ModbusTcpDto modbusDto) {
        byte[] unitBuff = modbusDto.getUnitBuff();
        return HexUtil.encodeHexStr(unitBuff);
    }

}
